package com.example.media.slice;

import com.example.media.CaptureAbility;
import com.example.media.ResourceTable;
import com.example.media.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.camera.CameraKit;
import ohos.media.camera.device.Camera;
import ohos.media.camera.device.CameraConfig;
import ohos.media.camera.device.CameraStateCallback;
import ohos.media.camera.device.FrameConfig;
import ohos.media.image.Image;
import ohos.media.image.ImageReceiver;
import ohos.media.image.common.ImageFormat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Time;
import java.util.Date;
import java.util.Timer;

public class CaptureAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private Button mBtnCapturePhoto;
    private Button mBtnCameraInfo;

    // SurfaceProvider对象
    private SurfaceProvider mSurfaceProvider;
    // SurfaceProvider提供的Surface对象
    private Surface mSurface = null;
    // 相机对象
    private Camera mCamera = null;
    // 事件处理对象
    private EventHandler mHandler = null;
    // 拍照后使用的图像接收器对象
    private ImageReceiver mImageReceiver = null;

    // 相机状态回调
    private CameraStateCallback cameraStateCallback = new CameraStateCallback() {
        @Override
        public void onCreated(Camera camera) {
            super.onCreated(camera);
            // 获取相机对象
            mCamera = camera;
            // 创建相机配置对象
            CameraConfig.Builder builder = camera.getCameraConfigBuilder();
            if (builder == null) {
                return;
            }
            // 为相机添加Surface
            builder.addSurface(mSurface);
            // 设置拍照的Surface
            builder.addSurface(mImageReceiver.getRecevingSurface());
            // 开始配置
            camera.configure(builder.build());
        }

        @Override
        public void onCreateFailed(String cameraId, int errorCode) {
            super.onCreateFailed(cameraId, errorCode);
            Utils.log("相机创建错误: " + errorCode + ",请检查权限!");
        }

        @Override
        public void onConfigured(Camera camera) {
            super.onConfigured(camera);
            // 创建帧配置对象
            FrameConfig.Builder builder =
                    camera.getFrameConfigBuilder(
                            Camera.FrameConfigType.FRAME_CONFIG_PREVIEW);
            // 添加Surface
            builder.addSurface(mSurface);
            // 开始循环帧捕获
            camera.triggerLoopingCapture(builder.build());
        }

        @Override
        public void onConfigureFailed(Camera camera, int errorCode) {
            super.onConfigureFailed(camera, errorCode);
            Utils.log("相机配置错误: " + errorCode);
        }

    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_capture);

        mBtnCapturePhoto = (Button) findComponentById(ResourceTable.Id_btn_capture_photo);
        mBtnCapturePhoto.setClickedListener(this);

        // 设置SurfaceProvider对象
        mSurfaceProvider = (SurfaceProvider) findComponentById(ResourceTable.Id_surface_provider);
        mSurfaceProvider.pinToZTop(true);
        mSurfaceProvider.getSurfaceOps().get().addCallback(new SurfaceOps.Callback() {
            @Override
            public void surfaceCreated(SurfaceOps surfaceOps) {
                // 获取Surface对象
                mSurface = surfaceOps.getSurface();
                // 创建相机对象
                createCamera();
            }

            @Override
            public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(SurfaceOps surfaceOps) {

            }
        });

        // 创建ImageReceiver对象
        mImageReceiver = ImageReceiver.create(1440, 1080, ImageFormat.JPEG, 5);
        // 设置拍照回调
        mImageReceiver.setImageArrivalListener((ImageReceiver imageReceiver)-> {
            // 文件名
            String fileName = "picture_" + System.currentTimeMillis() + ".jpg";
            // 创建照片文件
            final File file = new File(getExternalFilesDir("picture"), fileName);
            // 读取照片数据
            final Image image = imageReceiver.readNextImage();
            // 通过异步方法保存照片数据
            mHandler.postTask(()-> {
                // 通过Component对象读取二进制字节码
                Image.Component component = image.getComponent(ImageFormat.ComponentType.JPEG);
                byte[] bytes = new byte[component.remaining()];
                component.read(bytes);
                // 通过输出流保存数据
                FileOutputStream output = null;
                try {
                    output = new FileOutputStream(file);
                    output.write(bytes); // 写图像数据
                } catch (Exception e) {
                    Utils.log("写文件异常:" + e.getLocalizedMessage());
                } finally {
                    // 关闭输出流
                    if (output != null) {
                        try {
                            output.close();
                        } catch (IOException e) {
                            Utils.log(e.getLocalizedMessage());
                        }
                    }
                    // 释放照片数据
                    image.release();
                }
                getUITaskDispatcher().asyncDispatch(() ->{
                   Utils.showToast(CaptureAbilitySlice.this, "拍照成功!");
                });
            });
        });
    }

    @Override
    public void onClick(Component component) {
        // 拍摄照片
        // 获取拍照配置模板
        FrameConfig.Builder builder = mCamera.getFrameConfigBuilder(
                Camera.FrameConfigType.FRAME_CONFIG_PICTURE);
        // 配置拍照Surface
        builder.addSurface(mImageReceiver.getRecevingSurface());
        // 照片旋转90度，更改为横向
        builder.setImageRotation(90);
        try {
            // 启动单帧捕获(拍照)
            mCamera.triggerSingleCapture(builder.build());
        } catch (Exception e) {
            Utils.log(e.getLocalizedMessage());
        }
    }

    // 创建相机对象
    private void createCamera() {
        // 获取CameraKit对象
        CameraKit camerakit = CameraKit.getInstance(this);
        if (camerakit == null) {
            Utils.log("CameraKit获取失败!");
            return;
        }
        // 获取相机列表
        String[] cameraIds = camerakit.getCameraIds();
        if (cameraIds == null || cameraIds.length <= 0) {
            Utils.log("相机列表获取失败!");
            return;
        }

        mHandler = new EventHandler(EventRunner.current());

        // 创建相机对象
         camerakit.createCamera(cameraIds[0],
                 cameraStateCallback,
                 mHandler);
    }
}
